package com.shuang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shuang.mapper.StudentMapper;
import com.shuang.pojo.PageResult;
import com.shuang.pojo.Student;
import com.shuang.pojo.StudentQueryParam;
import com.shuang.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /*条件分页查询*/
    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {

        //1 设置分页参数
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());

        //2 执行查询
        List<Student> studentList = studentMapper.page(studentQueryParam);
        Page<Student> studentPage = (Page<Student>) studentList;

        return new PageResult<Student>(studentPage.getTotal(), studentPage.getResult());
    }

    /*添加学员*/
    @Override
    public void save(Student student) {
        //1 补全基本属性
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        //2 添加学员
        studentMapper.save(student);
    }

    /*根据id查询学员 -> 查询回显*/
    @Override
    public Student getInfo(Integer id) {
        return studentMapper.getInfo(id);
    }

    /*更新学员信息*/
    @Override
    public void update(Student student) {
        //1 补全基本属性
        student.setUpdateTime(LocalDateTime.now());

        //2
        studentMapper.update(student);
    }

    /*删除学员*/
    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }

    /*违纪处理*/
    @Override
    public void violate(Integer id, String score) {

        //1 根据id找到是哪个学员
        Student student = studentMapper.getInfo(id);

        //对传过来的score判断处理
        if (score.equals("0")){

        }else{
            //2 设置这个学员的违纪次数
            Short violationCount = student.getViolationCount();
            if (violationCount != null){
                student.setViolationCount(++violationCount);
            }else {
                student.setViolationCount(Short.parseShort("1"));
            }

//            设置这个学员的违纪扣分
            student.setViolationScore(Short.parseShort(score));

            // 3 更新操作时间
            student.setUpdateTime(LocalDateTime.now());
        }

        studentMapper.violate(student);

    }
}
